import Goods from "@/services/goods/typings"
import { EditFilled, HolderOutlined } from "@ant-design/icons"
import { Button, Input, InputNumber, Modal } from "antd"
import { useEffect, useState } from "react"
import {
  DndContext,
  closestCenter,
  KeyboardSensor,
  PointerSensor,
  useSensor,
  useSensors,
} from "@dnd-kit/core";
import {
  arrayMove,
  SortableContext,
  sortableKeyboardCoordinates,
  rectSortingStrategy,
  useSortable,
} from "@dnd-kit/sortable";
import { CSS } from "@dnd-kit/utilities"
import { message } from "tdesign-react";

interface GoodsInventoryInfoProps {
  value: Goods.GoodsStock[]
  onChange: (value: Goods.GoodsStock[]) => void
}

const Item: React.FC<{value: Goods.GoodsStock}> = props => {
  const [value, setValue] = useState<Goods.GoodsStock>(props.value)

  const onNameChange = (val: string) => {
    setValue({...value, stockName: val})
    props.value.stockName = val
  }
  const onPriceChange = (val: number | null) => {
    setValue({...value, stockPrice: val})
    props.value.stockPrice = val
  }
  const onLinePriceChange = (val: number | null) => {
    setValue({...value, stockLinePrice: val})
    props.value.stockLinePrice = val
  }
  const onNumChange = (val: number | null) => {
    setValue({...value, stockNum: val})
    props.value.stockNum = val
  }
  const onWeightChange = (val: number | null) => {
    setValue({...value, weight: val})
    props.value.weight = val
  }

  const {
    attributes,
    listeners,
    setNodeRef,
    transform,
    transition,
    isDragging
  } = useSortable({ id: props.value.id })

  const style = {
    transform: CSS.Transform.toString(transform),
    transition,
    zIndex: isDragging ? "100" : "auto",
    opacity: isDragging ? 0.3 : 1
  }

  useEffect(() => {
    setValue(props.value)
  }, [props.value])

  return <div
    className="flex border-t" ref={setNodeRef}
    style={{...style, background: '#f8f8f8', borderColor: 'var(--ant-color-split)'}}
  >
    <div className="w-3 shrink flex items-center justify-center cursor-move" {...listeners} {...attributes}>
      <HolderOutlined />
    </div>
    <div className="w-60 p-2">
      <Input value={value.stockName} onChange={({target}) => onNameChange(target.value)} />
      <div className="text-sm text-gray-500">{value.skuName}</div>
    </div>
    <div className="grow p-2">
      <InputNumber value={value.stockPrice} onChange={value => onPriceChange(value)} min={0} precision={2} controls={false} style={{width: '100%'}} />
    </div>
    <div className="grow p-2">
      <InputNumber value={value.stockNum} onChange={value => onNumChange(value)} min={0} precision={0} controls={false} style={{width: '100%'}} />
    </div>
    <div className="grow p-2">
      <InputNumber value={value.weight} onChange={value => onWeightChange(value)} min={0} precision={0} controls={false} style={{width: '100%'}} />
    </div>
  </div>
}

const GoodsInventoryInfo: React.FC<GoodsInventoryInfoProps> = props => {
  const sensors = useSensors(
    useSensor(PointerSensor),
    useSensor(KeyboardSensor, {
      coordinateGetter: sortableKeyboardCoordinates
    })
  );

  const handleDragEnd = (event: any) => {
    const { active, over } = event;

    if (active.id !== over.id) {
      const oldIndex = props.value.findIndex(it => it.id === active.id);
      const newIndex = props.value.findIndex(it => it.id === over.id);

      props.onChange?.(arrayMove(props.value, oldIndex, newIndex));
    }
  }
  const openBatchModal = (type: '价格' | '划线价' | '库存' | '重量') => {
    let _value: number | null = null
    Modal.confirm({
      icon: <EditFilled />,
      title: `批量设置${type}`,
      content: <InputNumber
        placeholder={type}
        onChange={val => _value = val}
        min={0}
        precision={['库存', '重量'].includes(type) ? 0 : 2}
        controls={false}
        style={{width: '100%'}}
      />,
      onOk: async () => {
        if (_value === null) {
          message.error(`请输入有效的${type}`)
          return Promise.reject()
        }
        switch (type) {
          case '价格': props.value.forEach(item => item.stockPrice = _value); break
          case '划线价': props.value.forEach(item => item.stockLinePrice = _value); break
          case '库存': props.value.forEach(item => item.stockNum = _value); break
          case '重量': props.value.forEach(item => item.weight = _value); break
        }
        props.onChange(props.value.map(it => ({...it})))
        return Promise.resolve()
      }
    })
  }

  return (
    <DndContext
      sensors={sensors}
      collisionDetection={closestCenter}
      onDragEnd={handleDragEnd}
    >
      <div className="flex flex-col">
        <div className="flex">
          <div className="w-3 shrink"></div>
          <div className="w-60 p-2">
            <span style={{color: '#ff4040'}}>* </span>
            <span>名称</span>
          </div>
          <div className="grow w-0 p-2">
            <span style={{color: '#ff4040'}}>* </span>
            <span>价格(元)</span>
          </div>
          <div className="grow w-0 p-2">
            <span style={{color: '#ff4040'}}>* </span>
            <span>库存</span>
          </div>
          <div className="grow w-0 p-2">重量(g)</div>
        </div>
        <SortableContext items={props.value} strategy={rectSortingStrategy}>
          {
            props.value.map((stock) => {
              return <Item key={stock.stockId || stock.fakeId} value={stock} />
            })
          }
        </SortableContext>
        <div className="flex p-2 gap-2 items-center">
          <div>批量设置:</div>
          <Button type="primary" onClick={() => openBatchModal('价格')} size="small">价格</Button>
          <Button type="primary" onClick={() => openBatchModal('库存')} size="small">库存</Button>
          <Button type="primary" onClick={() => openBatchModal('重量')} size="small">重量</Button>
        </div>
      </div>
    </DndContext>
  )
}

export default GoodsInventoryInfo
